const express = require('express');
const router = express.Router();
const Users = require('./../models/Users');
const Cookies = require('cookies');
require('./../utils/util')
//const cookieParser = require('cookie-parser');

let userInfo = {
  userId: '',
  userName: ''
};

let reData = (status = '', msg = '', result = '') => {

  return { status, msg, result }
};

router.use((req, res, next) => {

  // req.cookies = new Cookies(req, res);
  userInfo = req.cookies.get('userInfo') ? JSON.parse(req.cookies.get('userInfo')) : userInfo;
  next();
});

/** 登入 */
router.post('/login', (req, res) => {

  // 获取用户名和密码参数
  let params = req.body;

  // 首次加载，用户名密码都为空
  if(params.loadPage) {
  
    // 判断cookies是否存在用户
    if(req.cookies.get('userInfo')) {
      // 来自cookies
      res.json(reData('0', 'login: from cookies', userInfo));
    } else {
      // 没有cookies记录
      res.json(reData('0', 'login: no cookies', userInfo));
    }
  } else {

    Users.findOne({
      userName: params.userName,
      userPwd: params.userPwd
    }).then(_user => {

      if(_user) {

        req.cookies.set('userInfo', JSON.stringify({
          userId: _user.userId,
          userName: _user.userName
        }));

        res.json(reData('0', 'login: from mongoodb', _user));
      } else {

        res.json(reData('1', 'login: no this user', _user));
      }
    });
  }
});

/** 登出 */
router.post('/logout', (req, res) => {
  userInfo = {
    userId: '',
    userName: ''
  };
  req.cookies.set('userInfo', void 0);
  res.json(reData('0', 'logout', ''));
});

/** 列出购物车 */
router.get('/cartList', (req, res) => {

  Users.findOne({
    userId: userInfo.userId
  }).then(_user => {

    if(_user) {

      res.json(reData('0', "cartList", _user.cartList));
    } else {

      res.json(reData('1', "cartList: no such user", _user));
    }
  });
});

/** 购物车删除 */
router.post('/cart/del', (req, res) => {

  let productId = req.body.productId;
  Users.update({ userId: userInfo.userId },{
    // $pull删除
    $pull:{
      cartList: { productId }
    }
  }).then(newUser => {

    if(newUser) {

      res.json(reData('0', "del", newUser));
    }
  });
});

/** 购物车修改 */
router.post('/cart/edit', (req, res) => {

  let { productId, productNum, checked } = req.body
  Users.update({
    userId: userInfo.userId,
    'cartList.productId': productId
  }, {
    // $为查询出的数组部分
    'cartList.$.productNum': productNum,
    'cartList.$.checked': checked
  }).then(result => {

    // {n: 0, nModified: 0, ok: 1}
    if(result.ok == 1 && result.n >0) {

      res.json(reData('0', "edit", result));
    } else {

      res.json(reData('1', "edit: some error", result));
    }
  });
});

/** 全选反选 */
router.post('/editCheckAll', (req, res) => {

  let checkAll = req.body.checkAll ? '1' : '0';
  Users.findOne({ userId: userInfo.userId })
  .then(_user => {
    if(_user) {
      _user.cartList.forEach(item => {
        item.checked = checkAll;
      });

      _user.save()
      .then(newUser => {
        if(newUser) {

          res.json(reData('0', "editCheckAll", newUser));
        } else {

          res.json(reData('1', "editCheckAll: error", newUser));
        }
      });
    } else {

      res.json(reData('1', "editCheckAll: no such user", newUser));
    }
  });
});

/** 用户收获地址查询 */
router.get('/addressList', (req, res) => {

  let userId = userInfo.userId;
  Users.findOne({ userId })
  .then(_user => {
    if(_user) {

      res.json(reData('0', "addressList", _user.addressList));
    } else {

      res.json(reData('1', "addressList: no such user", _user));
    }
  });
});

/** 设置默认地址 */
router.post('/setDefault', (req, res) => {

  let userId = userInfo.userId;
  let addressId = req.body.addressId;
  Users.findOne({
    userId
  }).then(_user => {
    if(_user) {

      _user.addressList.forEach(address => {
        if(address.addressId == addressId) {
          address.isDefault = true;
        } else {
          address.isDefault = false;
        }
      });

      _user.save()
      .then(newUser => {
        if(newUser) {

          res.json(reData('0', "setDefault", newUser));
        } else {

          res.json(reData('1', "setDefault: save error", newUser));
        }
      });
    } else {

      res.json(reData('1', "setDefault: no such user", _user));
    }
  });
});

/** 删除地址 */
router.post('/delAddress', (req, res) => {

  let userId = userInfo.userId;
  let addressId = req.body.addressId
  Users.update({
    userId
  }, {
    $pull: {
      addressList: {addressId}
    }
  }).then(result => {

    res.json(reData('0', "delAddress", result));
  })
});

/** 生成订单 */
router.post('/payMent', (req, res) => {

  let userId = userInfo.userId;
  let addressId = req.body.addressId;
  let orderTotal = req.body.orderTotal;
  Users.findOne({
    userId
  }).then(_user => {
    if(_user) {

      // 获取地址信息
      let address = '';
      _user.addressList.forEach(_address => {
        if(addressId == _address.addressId) {
          address = _address;
        }
      });

      // 获取选中的商品
      let goodsList = []
      _user.cartList.filter(item => {
        if(item.checked == '1') {
          goodsList.push(item);
        }
      });

      // 随机码生成订单号
      let platfrom = '322';
      let r1 = Math.floor(Math.random() * 10)
      let r2 = Math.floor(Math.random() * 10)

      let sysDate = new Date().Format('yyyyMMddhhmmss');
      let createDate = new Date().Format('yyyy-MM-dd hh:mm:ss');
      let orderId = platfrom + r1 + sysDate + r2;

      var oneOrder = {
        orderId, orderTotal, address, goodsList, createDate,
        orderStatus: '1',
      };
      
      _user.orderList.push(oneOrder);

      _user.save()
      .then(newUser => {
        if(newUser) {

          res.json(reData('0', "payMent", {
            orderId, orderTotal
          }));
        } else {

          res.json(reData('1', "payMent: save error", newUser));
        }
      });
    } else {

      res.json(reData('1', "payMent: no such user", _user));
    }
  });
});

/** 查询order详情 */
router.get('/orderDetail', (req, res) => {

  let userId = userInfo.userId;
  let orderId = req.query.orderId;

  Users.findOne({
    userId
  }).then(_user => {

    if(_user) {

      let ol = _user.orderList;
      let order;

      if(ol.length > 0) {

        // 根据订单号查询
        ol.forEach(o => {
          console.log(o.orderId + '--' + orderId);
          if(o.orderId == orderId) {
            order = o;
          }
        });

        res.json(reData('0', "orderDetail", order));
      } else {

        res.json(reData('1', "orderDetail: no such order", _user));
      }
    } else {

      res.json(reData('1', "orderDetail: o such user", _user));
    }
  });
});

/** 查询购物车数量 */
router.get('/getCartCount', (req, res) => {
  let userId = userInfo.userId;

  if(userId) {
    Users.findOne({userId})
    .then(user => {
      if(user) {

        let cartList = user.cartList;

        let totalNum = cartList.reduce((total, item) => {
          return item.checked == '1' ? total + +item.productNum : total;
        }, 0);

        res.json(reData('0', '', totalNum));
      }
    });
  }
});


module.exports = router;
